package com.olive;

import java.util.Map;
import java.util.NoSuchElementException;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

public class FastUserRegister implements EnvironmentAware, ImportBeanDefinitionRegistrar {

	private Environment env;

	private Binder binder;

	public void setEnvironment(Environment environment) {
		this.env = environment;
		// bing binder
		binder = Binder.get(this.env);
	}

	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, 
			BeanDefinitionRegistry beanDefinitionRegistry) {
		Map<String, Map> multipleRedis;
		try {
			multipleRedis = binder.bind("fast.user", Map.class).get();
		} catch (NoSuchElementException e) {
			e.printStackTrace();
			return;
		}
		for (String key : multipleRedis.keySet()) {
			Map map = multipleRedis.get(key);
			 GenericBeanDefinition userDtoBean = new GenericBeanDefinition();
			 userDtoBean.setBeanClass(UserDto.class);
			 userDtoBean.getPropertyValues().add("userName", map.get("userName").toString());
			 userDtoBean.getPropertyValues().add("age", Integer.parseInt(map.get("age").toString()));
			 userDtoBean.setAutowireMode(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME);
			beanDefinitionRegistry.registerBeanDefinition(key, userDtoBean);
		}
		
	}

}
